<script lang="ts" setup>
import { useTemplateConfig } from "./composables/useTemplateConfig"

// 获取URL参数中的人设ID
const route = useRoute()
const personaId = route.params.id as string

// 使用模板配置业务逻辑
const {
  // 基本数据
  loading,
  personaInfo,
  activeTab,

  // 推荐模板相关
  templateList,
  showTemplateDialog,
  currentEditTemplate,
  templateForm,
  templateFormRef,
  templateRules,

  // 对标账号相关
  targetAccountList,
  showTargetAccountDialog,
  currentEditTargetAccount,
  targetAccountForm,
  targetAccountFormRef,
  targetAccountRules,

  // 方法
  handleTabChange,
  handleCreateTemplate,
  handleEditTemplate,
  handleDeleteTemplate,
  handleTemplateDialogConfirm,
  handleTemplateDialogCancel,
  handleCreateTargetAccount,
  handleEditTargetAccount,
  handleDeleteTargetAccount,
  handleTargetAccountDialogConfirm,
  handleTargetAccountDialogCancel,

  // 平台选项
  platformOptions,
  packageOptions,

  // 文件上传
  handleFileUpload,
  handleFileRemove
} = useTemplateConfig(personaId)

// Upload 组件引用
const uploadRef = ref()

// 文件超出限制时的处理 - 实现文件替换
function handleExceed(files: File[]) {
  // 清除现有文件
  uploadRef.value.clearFiles()

  // 获取新文件
  const file = files[0] as any

  // 验证文件
  const isValidType = ["video/mp4", "image/jpeg", "image/jpg", "image/png"].includes(file.type || "")
  const isValidSize = file.size / 1024 / 1024 < 10 // 10MB

  if (!isValidType) {
    ElMessage.error("仅支持 mp4/jpg/jpeg/png 文件")
    return
  }
  if (!isValidSize) {
    ElMessage.error("文件大小不能超过 10MB")
    return
  }

  // 生成新的文件ID并添加
  file.uid = Date.now()
  uploadRef.value.handleStart(file)

  ElMessage.success(`文件已替换：${file.name}`)
}

// 工具方法
function getPlatformTagBgColor(platform: string) {
  const colorMap: Record<string, string> = {
    抖音: "#C33142",
    小红书: "#FAE3E2",
    微信: "#07c160",
    微博: "#e6162d"
  }
  return colorMap[platform] || "#409eff"
}

function getPlatformTagTextColor(platform: string) {
  const colorMap: Record<string, string> = {
    抖音: "#ffffff",
    小红书: "#B11E1B",
    微信: "#ffffff",
    微博: "#ffffff"
  }
  return colorMap[platform] || "#ffffff"
}

// 文件预览相关方法
function isVideoFile(file: any) {
  return file.raw?.type?.startsWith("video/") || file.type?.startsWith("video/")
}

function getFilePreviewUrl(file: any) {
  if (file.url) {
    return file.url
  }
  if (file.raw) {
    return URL.createObjectURL(file.raw)
  }
  return ""
}

function handleImageError(event: Event) {
  const target = event.target as HTMLImageElement
  target.src = ""
}

function getPackageTagType(pkg: string): any {
  const typeMap: Record<string, string> = {
    "标准版": "version-standard",
    "Pro版": "version-pro",
    "Pro Max版": "version-pro-max"
  }
  return typeMap[pkg] || "version-standard"
}

function getPreviewIcon(type?: string) {
  return type === "video" ? "VideoPlay" : "Picture"
}

function getPreviewIconClass(type?: string) {
  return type === "video" ? "video-icon" : "image-icon"
}
</script>

<template>
  <div class="template-config-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <!-- 人设信息 -->
      <div v-if="personaInfo" class="persona-info">
        <h2 class="persona-title">{{ personaInfo.title }}</h2>
        <div class="persona-meta">
          <span class="meta-item">人设ID：{{ personaInfo.id }}</span>
          <span class="meta-item">所属行业：{{ personaInfo.industry }}</span>
          <span class="meta-item">创建时间：{{ personaInfo.createdAt }}</span>
        </div>
        <p class="persona-description">{{ personaInfo.description }}</p>
      </div>
    </div>

    <!-- 标签页切换 -->
    <div class="tabs-container">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="推荐模板管理" name="template" />
        <el-tab-pane label="对标账号管理" name="targetAccount" />
      </el-tabs>
    </div>

    <!-- 推荐模板列表 -->
    <div v-if="activeTab === 'template'" class="template-section">
      <div class="section-header">
        <h3 class="section-title">推荐模板列表</h3>
        <el-button type="primary" @click="handleCreateTemplate" class="primary-button">
          <el-icon><Plus /></el-icon>
          新增推荐模板
        </el-button>
      </div>

      <div class="template-table">
        <el-table
          :data="templateList"
          v-loading="loading"
          style="width: 100%"
          :header-cell-style="{ backgroundColor: '#ffffff', color: '#303133', fontWeight: '500', borderBottom: '1px solid #ebeef5' }"
        >
          <el-table-column prop="name" label="模板名称" min-width="150" show-overflow-tooltip />

          <el-table-column prop="platform" label="适用平台" align="center" width="140">
            <template #default="{ row }">
              <CustomTag
                :text="row.platform"
                :color="getPlatformTagTextColor(row.platform)"
                :background-color="getPlatformTagBgColor(row.platform)"
                size="small"
              />
            </template>
          </el-table-column>

          <el-table-column prop="workflowId" label="工作流ID" min-width="200" show-overflow-tooltip />

          <el-table-column prop="packages" label="可用套餐" align="center" min-width="160">
            <template #default="{ row }">
              <div class="package-tags">
                <CustomTag
                  v-for="pkg in (Array.isArray(row.packages) ? row.packages : [row.packages])"
                  :key="pkg"
                  :text="pkg"
                  :type="getPackageTagType(pkg)"
                  size="small"
                  class="package-tag"
                />
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="preview" label="样例展示" align="center" width="120">
            <template #default="{ row }">
              <div class="preview-cell">
                <el-icon class="preview-icon" :class="getPreviewIconClass(row.preview?.type)">
                  <component :is="getPreviewIcon(row.preview?.type)" />
                </el-icon>
                <span class="preview-name">{{ row.preview?.name }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="createdAt" label="创建时间" align="center" width="120" />

          <el-table-column label="操作" align="center" width="120" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button link size="small" @click="handleEditTemplate(row)">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button link size="small" type="danger" @click="handleDeleteTemplate(row)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 对标账号列表 -->
    <div v-if="activeTab === 'targetAccount'" class="target-account-section">
      <div class="section-header">
        <h3 class="section-title">对标账号列表</h3>
        <el-button type="primary" @click="handleCreateTargetAccount" class="primary-button">
          <el-icon><Plus /></el-icon>
          新增对标账号
        </el-button>
      </div>

      <div class="target-account-list">
        <div
          v-for="account in targetAccountList"
          :key="account.id"
          class="account-card"
        >
          <!-- 卡片头部：平台标签和操作按钮 -->
          <div class="card-header">
            <div class="platform-info">
              <CustomTag
                :text="account.platform"
                :color="getPlatformTagTextColor(account.platform)"
                :background-color="getPlatformTagBgColor(account.platform)"
                size="small"
                class="platform-tag"
              />
              <span class="account-id">{{ account.platform === '抖音' ? '抖音号' : '账号信息' }}：{{ account.accountInfo }}</span>
            </div>
            <div class="card-actions">
              <el-button link size="small" @click="handleEditTargetAccount(account)" class="action-btn">
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button link size="small" type="danger" @click="handleDeleteTargetAccount(account)" class="action-btn">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>

          <!-- 分析内容 -->
          <div class="card-content">
            <div class="content-label">分析内容：</div>
            <div class="content-text">{{ account.analysisContent }}</div>
          </div>

          <!-- 创建时间 -->
          <div class="card-footer">
            <span class="created-time">创建时间：{{ account.createdAt }}</span>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="!loading && targetAccountList.length === 0" class="empty-state">
          <el-empty description="暂无对标账号数据" />
        </div>
      </div>
    </div>

    <!-- 新增/编辑推荐模板弹窗 -->
    <el-dialog
      v-model="showTemplateDialog"
      :title="currentEditTemplate ? '编辑推荐模板' : '新增推荐模板'"
      width="600px"
      :close-on-click-modal="true"
    >
      <el-form
        ref="templateFormRef"
        :model="templateForm"
        :rules="templateRules"
        label-width="140px"
        class="template-form"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input
            id="template-name"
            v-model="templateForm.name"
            placeholder="如：30秒探店快剪"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="适用平台" prop="platform">
          <el-select
            id="template-platform"
            v-model="templateForm.platform"
            placeholder="选择平台"
            style="width: 100%"
          >
            <el-option
              v-for="option in platformOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="爆款工作流链路ID" prop="workflowId">
          <el-input
            id="template-workflowId"
            v-model="templateForm.workflowId"
            placeholder="如：WF_QUICK_REVIEW_30S"
            maxlength="100"
          />
        </el-form-item>

        <el-form-item label="可用套餐等级" prop="package">
          <el-radio-group id="template-package" v-model="templateForm.package">
            <el-radio
              v-for="option in packageOptions"
              :key="option.value"
              :value="option.value"
            >
              {{ option.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="样例预览">
          <div class="file-upload-area">
            <!-- 配置多文件上传方式：将 :limit="1" 改为更大的数值（如 :limit="5"），并在 handleFileUpload 方法中处理多文件逻辑 -->
            <el-upload
              ref="uploadRef"
              v-model:file-list="templateForm.fileList"
              :auto-upload="false"
              :on-change="handleFileUpload"
              :on-remove="handleFileRemove"
              :on-exceed="handleExceed"
              :limit="1"
              accept="video/*,image/*"
              action="#"
              :show-file-list="true"
              drag
            >
              <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
              <div class="el-upload__text">
                点击或拖拽文件到此处上传
                <em>点击上传</em>
              </div>
              <div class="el-upload__tip">
                支持上传 mp4/jpg/png 格式文件，大小不超过 10MB
              </div>
            </el-upload>

            <!-- 文件预览区域 -->
            <div v-if="templateForm.fileList?.length" class="file-preview-area">
              <div class="preview-header">
                <span class="preview-title">预览效果</span>
                <el-button
                  type="danger"
                  size="small"
                  @click="handleFileRemove"
                  class="remove-btn"
                >
                  移除文件
                </el-button>
              </div>

              <div class="preview-content">
                <template v-for="file in templateForm.fileList" :key="file.uid">
                  <!-- 视频预览 -->
                  <div v-if="isVideoFile(file)" class="video-preview">
                    <video
                      :src="getFilePreviewUrl(file)"
                      controls
                      class="preview-video"
                      preload="metadata"
                    >
                      您的浏览器不支持视频播放
                    </video>
                    <div class="file-info">
                      <span class="file-name">{{ file.name }}</span>
                      <span class="file-type">视频文件</span>
                    </div>
                  </div>

                  <!-- 图片预览 -->
                  <div v-else class="image-preview">
                    <img
                      :src="getFilePreviewUrl(file)"
                      :alt="file.name"
                      class="preview-image"
                      @error="handleImageError"
                    >
                    <div class="file-info">
                      <span class="file-name">{{ file.name }}</span>
                      <span class="file-type">图片文件</span>
                    </div>
                  </div>
                </template>
              </div>
            </div>

            <div v-else class="no-file-tip">
              未选择任何文件
            </div>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleTemplateDialogCancel">取消</el-button>
          <el-button type="primary" @click="handleTemplateDialogConfirm" class="primary-button">
            {{ currentEditTemplate ? '更新模板' : '创建模板' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增/编辑对标账号弹窗 -->
    <el-dialog
      v-model="showTargetAccountDialog"
      :title="currentEditTargetAccount ? '编辑对标账号' : '新增对标账号'"
      width="600px"
      :close-on-click-modal="true"
    >
      <el-form
        ref="targetAccountFormRef"
        :model="targetAccountForm"
        :rules="targetAccountRules"
        label-width="140px"
        class="target-account-form"
      >
        <el-form-item label="平台" prop="platform">
          <el-select
            id="target-platform"
            v-model="targetAccountForm.platform"
            placeholder="选择平台"
            style="width: 100%"
          >
            <el-option
              v-for="option in platformOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="对标账号信息" prop="accountInfo">
          <el-input
            id="target-accountInfo"
            v-model="targetAccountForm.accountInfo"
            placeholder="如：抖音号：Lilaoba_hotpot"
            maxlength="100"
          />
        </el-form-item>

        <el-form-item label="分析内容" prop="analysisContent">
          <el-input
            id="target-analysisContent"
            v-model="targetAccountForm.analysisContent"
            type="textarea"
            :rows="6"
            placeholder="请填写对此账号的详细分析，此内容将展示在商家版的品牌策划案中..."
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleTargetAccountDialogCancel">取消</el-button>
          <el-button type="primary" @click="handleTargetAccountDialogConfirm" class="primary-button">
            {{ currentEditTargetAccount ? '更新对标账号' : '创建对标账号' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
@import "./styles/index.scss";
.template-config-container {
  min-height: 100vh;
  background-color: #ffffff;
  padding: 24px;

  .page-header {
    padding: 24px 0;
    margin-bottom: 24px;

    .persona-info {
      .persona-title {
        font-size: 24px;
        font-weight: 600;
        color: #1f2937;
        margin: 0 0 12px 0;
      }

      .persona-meta {
        display: flex;
        gap: 24px;
        margin-bottom: 16px;

        .meta-item {
          font-size: 14px;
          color: #6b7280;
        }
      }

      .persona-description {
        font-size: 14px;
        color: #374151;
        line-height: 1.5;
        margin: 0;
      }
    }
  }

  .tabs-container {
    padding: 0;
    margin-bottom: 24px;

    :deep(.el-tabs__header) {
      margin-bottom: 0;
    }

    :deep(.el-tabs__item) {
      font-weight: 500;
    }
  }

  .template-section,
  .target-account-section {
    padding: 0;

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;

      .section-title {
        font-size: 18px;
        font-weight: 600;
        color: #1f2937;
        margin: 0;
      }
    }

    .template-table {
      border: 1px solid #ebeef5;
      border-radius: 4px;
      overflow: hidden;

      :deep(.el-table) {
        border: none;

        .el-table__header {
          th {
            background-color: #ffffff;
            border-bottom: 1px solid #ebeef5;
            height: 48px;

            .cell {
              font-weight: 500;
              color: #303133;
            }
          }
        }

        .el-table__body {
          tr {
            height: 56px;

            &:hover {
              background-color: #f5f7fa;
            }

            td {
              border-bottom: 1px solid #ebeef5;
              padding: 12px 0;

              .cell {
                color: #606266;
              }
            }
          }
        }
      }

      .package-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 4px;
        justify-content: center;
        align-items: center;
        min-height: 24px;

        .package-tag {
          margin: 0;
          white-space: nowrap;

          :deep(.custom-tag) {
            border-radius: 4px;
            font-size: 12px;
            height: 22px;
            line-height: 20px;
            padding: 0 8px;
            display: inline-block;
          }
        }
      }

      .preview-cell {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;

        .preview-icon {
          font-size: 16px;

          &.video-icon {
            color: #409eff;
          }

          &.image-icon {
            color: #67c23a;
          }
        }

        .preview-name {
          font-size: 12px;
          color: #6b7280;
          max-width: 60px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .action-buttons {
        display: flex;
        justify-content: center;
        gap: 8px;

        .el-button {
          padding: 4px;
          margin: 0;
          border: none;
          background: transparent;

          &:hover {
            background-color: #f5f7fa;
            border-radius: 4px;
          }
        }
      }
    }

    .target-account-list {
      display: flex;
      flex-direction: column;
      gap: 16px;

      .account-card {
        background: #ffffff;
        border: 1px solid #e5e7eb;
        border-radius: 12px;
        padding: 20px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        transition: all 0.2s ease;

        &:hover {
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          border-color: #d1d5db;
        }

        .card-header {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          margin-bottom: 16px;

          .platform-info {
            display: flex;
            align-items: center;
            gap: 12px;
            flex: 1;

            .platform-tag {
              :deep(.custom-tag) {
                border-radius: 4px;
                font-size: 12px;
                font-weight: 500;
                padding: 4px 8px;
                border: none;
              }
            }

            .account-id {
              font-size: 14px;
              color: #374151;
              font-weight: 500;
            }
          }

          .card-actions {
            display: flex;
            gap: 8px;
            opacity: 0.7;
            transition: opacity 0.2s ease;

            .action-btn {
              padding: 4px;
              border-radius: 4px;
              color: #6b7280;

              &:hover {
                background-color: #f3f4f6;
                color: #374151;
              }

              &.el-button--danger:hover {
                background-color: #fee2e2;
                color: #dc2626;
              }
            }
          }

          &:hover .card-actions {
            opacity: 1;
          }
        }

        .card-content {
          margin-bottom: 16px;

          .content-label {
            font-size: 14px;
            font-weight: 500;
            color: #374151;
            margin-bottom: 8px;
          }

          .content-text {
            font-size: 14px;
            color: #6b7280;
            line-height: 1.6;
            text-align: justify;
          }
        }

        .card-footer {
          padding-top: 12px;
          border-top: 1px solid #f3f4f6;

          .created-time {
            font-size: 12px;
            color: #9ca3af;
          }
        }
      }

      .empty-state {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 200px;
        border: 1px dashed #e5e7eb;
        border-radius: 8px;
        background-color: #fafafa;
      }
    }
  }

  .template-form,
  .target-account-form {
    .file-upload-area {
      width: 100%;

      :deep(.el-upload-dragger) {
        width: 100%;
        height: 140px;
      }

      .no-file-tip {
        text-align: center;
        color: #9ca3af;
        font-size: 14px;
        margin-top: 8px;
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }

  // CustomTag 样式优化
  .platform-tag {
    :deep(.custom-tag) {
      border-radius: 4px;
      font-size: 12px;
      font-weight: 500;
      padding: 2px 8px;
      border: none;
    }
  }

  // 文件上传区域样式
  .file-upload-area {
    .file-info {
      margin-top: 10px;

      .file-item {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 12px;
        background-color: #f5f7fa;
        border-radius: 6px;
        border: 1px solid #e1e5e9;

        .el-icon {
          color: #409eff;
        }

        span {
          flex: 1;
          font-size: 14px;
          color: #606266;
        }
      }
    }

    .native-upload {
      text-align: center;
      padding: 10px;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      background-color: #fafafa;

      &:hover {
        border-color: #409eff;
        background-color: #f0f8ff;
      }
    }
  }

  // 文件预览区域样式
  .file-preview-area {
    margin-top: 16px;
    padding: 16px;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    background-color: #fafafa;

    .preview-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;

      .preview-title {
        font-weight: 500;
        color: #303133;
        font-size: 14px;
      }

      .remove-btn {
        font-size: 12px;
        padding: 4px 8px;
      }
    }

    .preview-content {
      .video-preview,
      .image-preview {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 8px;
      }

      .preview-video {
        max-width: 100%;
        max-height: 200px;
        border-radius: 4px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }

      .preview-image {
        max-width: 100%;
        max-height: 200px;
        object-fit: contain;
        border-radius: 4px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }

      .file-info {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 4px;
        text-align: center;

        .file-name {
          font-size: 14px;
          color: #303133;
          font-weight: 500;
          max-width: 200px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .file-type {
          font-size: 12px;
          color: #909399;
          padding: 2px 8px;
          background-color: #e4e7ed;
          border-radius: 12px;
        }
      }
    }
  }

  // 主要按钮样式
  .primary-button {
    background-color: #030212 !important;
    border-color: #030212 !important;

    &:hover {
      background-color: #1a1a2e !important;
      border-color: #1a1a2e !important;
    }

    &:active {
      background-color: #000000 !important;
      border-color: #000000 !important;
    }

    &:focus {
      background-color: #030212 !important;
      border-color: #030212 !important;
    }
  }
}
</style>
